const TIME_OUT = 60 * 60 * 24 * 7; // 7天

export function getStorage(key, def = null) {
  const stringData = uni.getStorageSync(key);

  if (!stringData) return def;

  const data = JSON.parse(stringData);

  const { value, expire } = data;

  if (expire && expire < Date.now()) {
    removeStorage(key);
    return def;
  }
  return value;
}

export function setStorage(key, value, expire = TIME_OUT) {
  const time = Date.now();

  const stringData = JSON.stringify({
    value,
    time,
    expire: expire ? time + expire * 1000 : 0,
  });

  uni.setStorageSync(key, stringData);
}

export function removeStorage(key) {
  uni.removeStorageSync(key);
}

export function clearStorage() {
  uni.clearStorageSync();
}
